package com.carcenter.order.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.carcenter.common.constant.appointment.AppointmentConstant;
import com.carcenter.common.pojo.personnel.StoreManager;
import com.carcenter.common.pojo.personnel.UserDto;
import com.carcenter.common.result.Result;
import com.carcenter.common.result.enums.impl.BusinessCode;
import com.carcenter.common.result.enums.impl.ResultCode;
import com.carcenter.order.entity.AppointmentProcess;
import com.carcenter.order.service.IAppointmentProcessService;
import com.personnel.client.StaffApi;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author car
 * @since 2025-07-16
 */
@RestController
@RequestMapping("/appointment-process")
public class AppointmentProcessController {

    @Autowired
    StaffApi staffApi;

    @Autowired
    IAppointmentProcessService appointmentProcessService;

    @GetMapping("/getAppointmentProcessListByAppointmentId/{appointmentId}")
    public Result<List<AppointmentProcess>> getAppointmentProcessListByAppointmentId(@PathVariable Integer appointmentId) {
        LambdaQueryWrapper<AppointmentProcess> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AppointmentProcess::getAppointmentId, appointmentId)
                .orderByAsc(AppointmentProcess::getAppointmentStatus);
        List<AppointmentProcess> list = appointmentProcessService.list(queryWrapper);
        List<Integer> staffIds = new ArrayList<>();
        List<Integer> userIds = new ArrayList<>();
        for (AppointmentProcess appointmentProcess : list) {
            staffIds.add(appointmentProcess.getStaffId());
            userIds.add(appointmentProcess.getUserId());
        }

        List<UserDto> userDtos = new ArrayList<>();
        Result<List<UserDto>> result = staffApi.getUserDtosByUserIds(userIds);
        if(result!=null && result.getCode()== ResultCode.SUCCESS.getCode()){
            List<UserDto> data = result.getData();
            userDtos=data!=null?data:new ArrayList<>();
        }
        Map<Integer, UserDto> userDtoMap = userDtos.stream().collect(Collectors.toMap(UserDto::getId, userDto -> userDto));

        List<StoreManager> staffList = new ArrayList<>();
        Result<List<StoreManager>> result2 = staffApi.getStoreManagersByManagerIds(staffIds);
        if(result2!=null && result2.getCode()== ResultCode.SUCCESS.getCode()){
            List<StoreManager> data2 = result2.getData();
            staffList=data2!=null?data2:new ArrayList<>();
        }
        Map<Integer, StoreManager> staffDtoMap = staffList.stream().collect(Collectors.toMap(StoreManager::getId, staff -> staff));


        for (AppointmentProcess appointmentProcess : list) {
            appointmentProcess.setUserDto(userDtoMap.get(appointmentProcess.getUserId()));
            appointmentProcess.setStaff(staffDtoMap.get(appointmentProcess.getStaffId()));
        }

        return Result.ok(list);
    }

    @PostMapping("/invalidAppointment/{appointmentId}/{userId}")
    public Result<String> invalidAppointment(@PathVariable Integer appointmentId, @PathVariable Integer userId) {
        //查询是否已经支付
        LambdaQueryWrapper<AppointmentProcess> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AppointmentProcess::getAppointmentId, appointmentId)
                    .orderByAsc(AppointmentProcess::getOperationTime);
        List<AppointmentProcess> list = appointmentProcessService.list(queryWrapper);
        if(list.size()==2 && list.get(1).getAppointmentStatus().equals(AppointmentConstant.ALREADY_PAID) ) {
            return Result.ok(BusinessCode.PAID_INVALID_APPOINTMENT.getMessage());
        }else if (list.size()==2 && list.get(1).getAppointmentStatus().equals(AppointmentConstant.ALREADY_CANCELLED)){
            return Result.ok(BusinessCode.CANCEL_INVALID_APPOINTMENT.getMessage());
        }else {
            //新建无效
            AppointmentProcess appointmentProcess = new AppointmentProcess();
            appointmentProcess.setAppointmentId(appointmentId);
            appointmentProcess.setUserId(userId);
            appointmentProcess.setAppointmentStatus(AppointmentConstant.ALREADY_INVALID);
            appointmentProcess.setOperationTime(LocalDateTime.now());
            appointmentProcessService.save(appointmentProcess);
            return Result.ok(BusinessCode.UNPAID_INVALID_APPOINTMENT.getMessage());
        }

    }
}
